import { NextResponse } from "next/server";
import { UserService } from "@/utils/prisma";
import User from "../../../../models/User";


export async function POST(request: Request) {
    const { action, params } = await request.json();
    try {
        switch (action) {
            case "login": {
                const { email, password } = params
                const login = await UserService.login(email, password)
                if (login) {
                    return NextResponse.json({ data: login, status: 200, message: "success" });
                } else {
                    return NextResponse.json({ data: login, status: 200, message: "fail" });
                }
            }
            case "register": {
                const { name, email, password } = params
                const registerData = await UserService.register(name, email, password)
                if (registerData) {
                    return NextResponse.json({ data: [], status: 200, message: "success" });
                } else {
                    return NextResponse.json({ data: [], status: 200, message: "fail" });
                }
            }
            case "refresh": {
                const { oldRefreshToken } = params
                const token = await UserService.refreshToken(oldRefreshToken) as any
                if (token) {
                    return NextResponse.json({
                        data: {
                            token: token.token,
                            refreshToken: token.refreshToken
                        }, status: 200, message: "success"
                    });
                } else {
                    return NextResponse.json({
                        data: {}, status: 200, message: "fail"
                    }, { status: 401 });
                }

            }
            default:
                return NextResponse.json({ status: 400, error: "Invalid action" });
        }
    } catch (error) {
        console.error(error);
        return NextResponse.json({
            status: 500,
            error: "Failed to process request",
        });
    }
}
